package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.User;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.ErrorResult;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component // spring的
public class UserManager {

    @Reference // dubbo的
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 保存用户
    public ResponseEntity save(User user) {
        Long userId = userService.save(user);
        return ResponseEntity.ok(userId);
    }

    // 根据手机号查询
    public ResponseEntity findByPhone(String phone) {
        User user = userService.findByPhone(phone);
        return ResponseEntity.ok(user);
    }

    public void sendSmsCode(String phone) {
        // 1.生成验证码
        // String smsCode = RandomUtil.randomNumbers(6);
        String smsCode = "123456";

        // 2.发送短信
        // smsTemplate.sendSms(phone, smsCode);

        // 3.将验证码存入redis
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + phone, smsCode, Duration.ofMinutes(5));
    }

    public ResponseEntity regAndLogin(String phone, String verificationCode) {
        // 1.对比验证码
        // 从redis中获取
        String redisCode = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        if (!StrUtil.equals(verificationCode, redisCode)) {
            // 对比不正确，返回错误提示
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }
        // 对比正确，清除验证码
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE + phone);
        // 2.手机号查询
        User user = userService.findByPhone(phone);
        boolean isNew;
        if (user == null) {
            // 新用户
            isNew = true;
            // 完成注册
            user = new User();
            user.setPhone(phone);
            user.setPassword(ConstantUtil.INIT_PASSWORD);
            Long userId = userService.save(user);
            user.setId(userId);

        } else {
            // 老用户
            isNew = false;
        }

        // 3.制作token
        user.setPassword(null);
        Map<String, Object> map = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(map);
        // 设置token续期
        String json = JSON.toJSONString(user);
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(1));

        // 4.返回结果
        Map resultMap = new HashMap();
        resultMap.put("isNew", isNew);
        resultMap.put("token", token);
        return ResponseEntity.ok(resultMap);
    }
}